// 正态分布图
// const jstat = require('jstat');
const jstat = require('../jstat/jstat.js');

// 定义函数，接受样本数组作为参数
function getNormalDistributionData(sampleArray) {
  // 计算样本数组的均值和标准差
  const mean = sampleArray.reduce((sum, value) => sum + value, 0) / sampleArray.length;
  const variance = sampleArray.reduce((sum, value) => sum + Math.pow(value - mean, 2), 0) / sampleArray.length;
  const stdDev = Math.sqrt(variance);

  // 计算概率密度
  const probabilityDensities = [];
  const minValue = Math.min(...sampleArray);
  const maxValue = Math.max(...sampleArray);
  const step = (maxValue - minValue) / 100; // 为了精细绘制，将范围细分
  let currentValue = minValue;
  while (currentValue <= maxValue) {
    const density = jstat.normal.pdf(currentValue, mean, stdDev);
    probabilityDensities.push(density);
    currentValue += step;
  }

  // 准备绘图数据
  const xValues = [];
  currentValue = minValue;
  while (currentValue <= maxValue) {
    xValues.push(currentValue);
    currentValue += step;
  }

  // 计算竖线位置
  const meanLine = mean;
  const oneStdDevLines = [mean - stdDev, mean + stdDev];
  const twoStdDevLines = [mean - 2 * stdDev, mean + 2 * stdDev];
  const threeStdDevLines = [mean - 3 * stdDev, mean + 3 * stdDev];

  return {
    xValues,
    probabilityDensities,
    meanLine,
    oneStdDevLines,
    twoStdDevLines,
    threeStdDevLines
  };
}

module.exports = getNormalDistributionData;
